'use strict';
// 公共云函数模块引入
const {
	appId,
	appSecret,
	getToken
} = require('wx-common')

exports.main = async (event, context) => {
	// 初始化数据库
	const db = uniCloud.database();
	// event中获取用户code
	const {
		code
	} = event;
	const res = await uniCloud.httpclient.request(
		"https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret +
		"&js_code=" + code + "&grant_type=authorization_code", {
			dataType: "json"
		}
	)
	// 获取用户openid
	const openid = res.data.openid;

	let dbRes = await db.collection("users").where({
		openid: openid
	}).get();

	const token = getToken(openid);
	const {
		v4: uuidv4
	} = require('uuid');
	const userId = uuidv4();
	let userData;
	if (dbRes.affectedDocs <= 0) {
		userData = {
			openid: openid,
			userId: userId,
			nickName: "微信用户",
			avatarUrl: "",
			token: token,
			score: 0,
			level: 1, // 初始化等级为1
			levelProgress: 0, // 初始化等级进度为0
			tasks: [ // 初始化任务列表，可以根据实际需求定义任务结构
				{
					id: 1,
					description: "每日签到（奖励随机翻倍）",
					isCompleted: false,
					value: 5
				},
				{
					id: 2,
					description: "今日在热销榜消费一次",
					isCompleted: false,
					value: 10
				},
				{
					id: 3,
					description: "今日在季节限定消费一次",
					isCompleted: false,
					value: 10
				}
				// 添加更多任务...
			],
			coupon: [{
				list: [{
					money: "5",
					title: "满15减5",
					ticket: "新人优惠券任意使用",
					seller_name: "Happy Tea官方旗舰店",
					end_time: "2023-11-1 12:00",
					remark: "all",
					CouponId: 1
				}]
			}]
		}

		await db.collection("users").add(userData);
	} else {
		userData = dbRes.data[0];
	}

	delete userData["openid"];
	userData["token"] = token;
	return userData;

};